﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace HandBrake_Encoder
{
    public partial class handBrakeBatchEncoder : Form
    {

        #region Fields and Properties

        private string handBrakeCLI;
        private string handBrakeCMD;
        
        delegate void RemoveListItemCallBack();
        ToolTip handBrakeCMDTextBoxToolTip = new ToolTip();
        ToolTip handBrakeCLILocationTextBoxToolTip = new ToolTip();
        ToolTip encodeButtonToolTip = new ToolTip();
        ToolTip fileRemoveButtonToolTip = new ToolTip();
        ToolTip folderSelectButtonToolTip = new ToolTip();
        ToolTip folderRecursiveCheckBoxToolTip = new ToolTip();
        ToolTip encodeLocationButtonToolTip = new ToolTip();
        ToolTip encodeLocationTextBoxToolTip = new ToolTip();
        #endregion

        #region Methods
        public handBrakeBatchEncoder()
        {
            InitializeComponent();

            handBrakeCLI = Properties.Settings.Default.HandBrakeCLILocation;
            handBrakeCMD = Properties.Settings.Default.HandBrakeCMD;
            folderBrowserDialog.RootFolder = Environment.SpecialFolder.MyComputer;
            folderBrowserDialog.ShowNewFolderButton = false;
            
            encodeFolderBrowserDialog.RootFolder = Environment.SpecialFolder.MyComputer;
            encodeFolderBrowserDialog.ShowNewFolderButton = false;

            encodeLocationTextBox.Text = Properties.Settings.Default.DefaultEncodeLocation;
            
            handBrakeCLIOpenFileDialog.InitialDirectory = Environment.SpecialFolder.ProgramFiles.ToString();
            handBrakeCLIOpenFileDialog.Filter = "HandBrakeCLI|Handbrakecli.exe";

            handBrakeCMDTextBox.Text = handBrakeCMD;

            handBrakeCLILocationTextBox.Text = handBrakeCLI;
            folderRecursiveCheckBox.Checked = true;
                        
            handBrakeCMDTextBoxToolTip.SetToolTip(handBrakeCMDTextBox, "Paste in here the query from handbrake. Remove the -i and -o sections of the query.");
            handBrakeCLILocationTextBoxToolTip.SetToolTip(handBrakeCLILocationTextBox, "Location of the HandBrake CLI Executable.");
            encodeButtonToolTip.SetToolTip(encodeButton, "Start the encode process.");
            fileRemoveButtonToolTip.SetToolTip(fileRemoveButton, "Remove item from the list.");
            folderSelectButtonToolTip.SetToolTip(folderSelectButton, "Select the folder to search for AVI files.\r\n WARNING can take a long time if recursive is selected.");
            folderRecursiveCheckBoxToolTip.SetToolTip(folderRecursiveCheckBox, "Recursively search the selected folder.");
            encodeLocationButtonToolTip.SetToolTip(encodeLocationButton, "Select the output folder.");
            encodeLocationTextBoxToolTip.SetToolTip(encodeLocationTextBox, "Add your default to the settings.settings file so you dont have to select every time.");
        }
        
        void DirSearch(string sDir)
         {
            try
            {                
                if (folderRecursiveCheckBox.Checked)
                {
                    
                    foreach (string d in Directory.GetDirectories(sDir))
                    {
                        
                        foreach (string f in Directory.GetFiles(d, "*.avi"))
                        {
                            this.folderFileListBox.Items.Add(f);
                        }
                        DirSearch(d);

                    }
                }
            }
            catch (System.Exception excpt)
            {
                Console.WriteLine(excpt.Message);
            }
        }

        private void encodeFiles()
        {
            string handbrake;
                        
            if (folderFileListBox.Items.Count > 0)
            {
                string source = folderFileListBox.Items[0].ToString();
                string destination = encodeLocationTextBox.Text + source.Substring(source.LastIndexOf(@"\"), source.Length - source.LastIndexOf(@"\"));
                if (this.folderFileListBox.InvokeRequired)
                {
                    RemoveListItemCallBack d = new RemoveListItemCallBack(RemoveListItem);
                    this.Invoke(d);
                }
                else
                {
                    RemoveListItem();
                }
                destination = destination.Replace(@".avi", @".m4v");

                handbrake = " -i " + '\u0022' + source + '\u0022';
                handbrake += " -o " + '\u0022' + destination + '\u0022';
                handbrake += " " + handBrakeCMDTextBox.Text;                
                Console.WriteLine(handBrakeCLILocationTextBox.Text + " " + handbrake);

                Process myprocess = Process.Start(handBrakeCLILocationTextBox.Text, handbrake);
                myprocess.EnableRaisingEvents = true;
                myprocess.Exited += new EventHandler(myprocess_exited);                
            }
            else
            {
                MessageBox.Show("Encoding has finished", "Done", MessageBoxButtons.OK);
            }
        }
        private void RemoveListItem()
        {
            folderFileListBox.Items.RemoveAt(0);
        }
        #endregion

        #region Events
        private void folderSelectButton_Click(object sender, EventArgs e)
        {
            DialogResult result = folderBrowserDialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                this.folderFileListBox.Items.Clear();
                folderTextBox.Text = folderBrowserDialog.SelectedPath;
                foreach (string f in Directory.GetFiles(folderBrowserDialog.SelectedPath, "*.avi"))
                {
                    this.folderFileListBox.Items.Add(f);
                }
                DirSearch(folderBrowserDialog.SelectedPath);
            }
        }        

        private void encodeLocationButton_Click(object sender, EventArgs e)
        {
            DialogResult result = encodeFolderBrowserDialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                encodeLocationTextBox.Text = encodeFolderBrowserDialog.SelectedPath;
            }
        }        

        private void handBrakeCLIButton_Click(object sender, EventArgs e)
        {
            DialogResult result = handBrakeCLIOpenFileDialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                handBrakeCLILocationTextBox.Text = handBrakeCLIOpenFileDialog.FileName;
            }
        }        

        private void encodeButton_Click(object sender, EventArgs e)
        {
            encodeFiles();
        }

        private void myprocess_exited(object sender, EventArgs e)
        {
            encodeFiles();
        }

        private void fileRemoveButton_Click(object sender, EventArgs e)
        {
            if (this.folderFileListBox.Items.Count > 0)
            {
                int selected = folderFileListBox.SelectedIndex;
                if (selected != -1)
                {
                    this.folderFileListBox.Items.RemoveAt(this.folderFileListBox.SelectedIndex);
                    if (selected == 0)
                    {
                        folderFileListBox.SelectedIndex = 0;
                    }
                    else
                    {
                        folderFileListBox.SelectedIndex = --selected;
                    }
                }
                else
                {
                    folderFileListBox.SelectedIndex= 0;
                }
            }
        }

        private void fileUpButton_Click(object sender, EventArgs e)
        {
            if (this.folderFileListBox.SelectedIndex == -1 || this.folderFileListBox.SelectedIndex == 0)
                return;

            Object select, previous, temp;
            select = folderFileListBox.Items[folderFileListBox.SelectedIndex];
            previous = folderFileListBox.Items[folderFileListBox.SelectedIndex - 1];
            temp = select;
            select = previous;
            previous = temp;
            folderFileListBox.Items[folderFileListBox.SelectedIndex] = select;
            folderFileListBox.Items[folderFileListBox.SelectedIndex - 1] = previous;

            folderFileListBox.SelectedIndex--;	
        }

        private void fileDownButton_Click(object sender, EventArgs e)
        {
            if (this.folderFileListBox.SelectedIndex == -1 || this.folderFileListBox.SelectedIndex == folderFileListBox.Items.Count - 1)
                return;

            Object select, next, temp;
            select = folderFileListBox.Items[folderFileListBox.SelectedIndex];
            next = folderFileListBox.Items[folderFileListBox.SelectedIndex + 1];
            temp = select;
            select = next;
            next = temp;
            folderFileListBox.Items[folderFileListBox.SelectedIndex] = select;
            folderFileListBox.Items[folderFileListBox.SelectedIndex + 1] = next;

            folderFileListBox.SelectedIndex++;
        }
        #endregion

        private void handBrakeCMDTextBox_MouseHover(object sender, EventArgs e)
        {
            

        }
    }
}
